<?php


namespace app\api\controller\device;


use app\module\code\Code;

use app\module\hardwareCloud\HardwareClout;
use think\facade\Db;

class Pwd
{
    public function list()
    {

        $lock_id = input("lock_id");
        $pwdS = Db::name("pwd")->where(["lock_id" => $lock_id])->whereNull("deleted_at")->select()->toArray();
        return json(Code::CodeOk([
            "data" => $pwdS
        ]));
    }

    public function add()
    {
        $lock_id = input("lock_id");
        $pwd = input("pwd");
        $pwd_name = input("pwd_name");
        $end_time = strtotime(input("end_time"));
        $lock = Db::name("lock")->where(["lock_id" => $lock_id])->find();
        if (strlen($pwd)<8){
            return json(Code::CodeErr(1001,"密码不能小于8位"));
        }

       $addres= HardwareClout::WifiLock()->PwdAdd($lock["lock_sn"], $pwd, $lock["device_cid"], time(), $end_time);
        if($addres["err"]){
            return json(Code::CodeErr(1000,$addres["err"]));
        }
        Db::name("pwd")->insert([
            "lock_id" => $lock_id,
            "pwd" => $pwd,
            "pwd_name" => $pwd_name,
            "end_time" => $end_time,
            "created_at" => time(),
        ]);
        return json(Code::CodeOk([]));
    }


    public function del()
    {
        $lock_id = input("lock_id");
        $pwd_id = input("pwd_id");
        $lock = Db::name("lock")->where(["lock_id" => $lock_id])->find();
        $pwd = Db::name("pwd")->where(["pwd_id" => $pwd_id])->find();
        $addres= HardwareClout::WifiLock()->PwdDel($lock["lock_sn"], $pwd["pwd"], $lock["device_cid"]);
        if($addres["err"]){
            return json(Code::CodeErr(1000,$addres["err"]));
        }
        Db::name("pwd")->where(["pwd_id" => $pwd_id])->update(["deleted_at"=>date("Y-m-d H:i:s")]);
        return json(Code::CodeOk([]));
    }
}
